package com.demo.webflux.spring5core.test.service;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.demo.webflux.spring5core.framework.aop.aspect.JoinPoint;

public class LogAspect {

	private final Logger log = LoggerFactory.getLogger(getClass());

	// 在调用一个方法之前，执行before
	public void before(JoinPoint joinPoint) {
		// MethodInvocation是JoinPoint的实现类，而MethodInvocation又是在JdkDynamicAopProxy的invoke方法中实例化的，即每个被代理对象的业务方法会对应一个MethodInvocation实例
		// 也就是说MethodInvocation的生命周期是被代理对象中业务方法的生命周期的对应。调用JoinPoint的setUserAttribute方法可以在JoinPoint中自定义属性，调用getUserAttribute方法可以获取自定义属性的值
		joinPoint.setUserAttribute("startTime_" + joinPoint.getMethod().getName(), System.currentTimeMillis());
		// 这个逻辑由用户自己写
		log.info("invoker before method!!!" + "\nTargetObject: " + joinPoint.getThis() + "\nArgs: " + Arrays.toString(joinPoint.getArguments()));
	}

	// 在调用一个方法之后执行after
	public void after(JoinPoint joinPoint) {
		log.info("invoke after method!!!" + "nTargetObject: " + joinPoint.getThis() + "\nArgs: " + Arrays.toString(joinPoint.getArguments()));
		long startTime = (Long)joinPoint.getUserAttribute("startTime_" + joinPoint.getMethod().getName());
		long endTime = System.currentTimeMillis();
		log.info("use time: " + (endTime - startTime));
	}

	public void AfterThrowing(JoinPoint joinPoint, Throwable ex) {
		log.info("出现异常" + "\nTargetObject: " + joinPoint.getThis() + "\nArgs: " + Arrays.toString(joinPoint.getArguments()) + "\nThrows: " + ex.getMessage());
	}

}
